<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="hidden" id="id" th:value="${param.id[0]}"/>
    <h4></h4>
    <div><span id="search"></span>次查看,共有<span id="vote"></span>人投票</div>
<form id="voteForm">
</form>
<a href="/index" class="btn">返回首页</a>

<script type="text/javascript" th:src="@{/jquery-3.7.1.js}"></script>
<script type="text/javascript">
    $(function (){
        const id = document.getElementById("id").value;
        loadData(id);
    })
    document.getElementById('voteForm').addEventListener('submit', async (e) => {
        e.preventDefault();

        const formData = new FormData(e.target);
        const selectedOptionId = formData.get('vote');

        if (!selectedOptionId) {
            alert('请选择一个选项');
            return;
        }

        try {
            const response = await fetch('/api/vote', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    optionId: selectedOptionId
                })
            });

            const result = await response.json();

            if (response.ok) {
                alert('投票成功！');
                // 刷新页面或更新投票结果
                location.reload();
            } else {
                alert(result.message || '投票失败');
            }
        } catch (error) {
            console.error('投票提交错误:', error);
            alert('网络错误，请稍后再试');
        }
    });
    function loadData(id){
        $.getJSON("/options/" + id,function (res){
            const title = res[0].subjects.title;
            console.log(res)
            document.getElementsByTagName("h4")[0].innerHTML = title;
            const search = res[0]['subjects']['viewTimes'];
            const vote = res[0]['subjects']['totalVotes'];
            document.getElementsByTagName("span")[0].innerHTML = search;
            document.getElementsByTagName("span")[1].innerHTML = vote;
            var strbody = '';
            for (var i = 0; i < res.length; i++) {
                strbody += `${i + 1}<input type="radio" name="vote" value="${res[i]['optContent']}">${res[i]['optContent']}
                            ${res[i]['vote']}票 ${Math.round((res[i].vote / res[i].subjects.viewTimes) * 100)}%
                         <br>`;
            }
            strbody+='<input type="submit" value="我要投票">'

            $("#voteForm").html(strbody)
        })
    }

</script>
</body>
</html>